<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Test</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
</head>
<style>
    /*#chat { margin: 0 auto; width: 100px; text-align: center; }*/
    /*#show { height: 200px; }*/
    /*.left { text-align: left; }*/
    /*.right { text-align: right; }*/
</style>
<body>
<!-- 聊天区域 -->
<div id="chat" class="layui-container">
    <!-- 连接成功, 欢迎 -->
    <div id='welcome'></div>
    <!-- 发送消息 -->
    <div id='message'>
        <input type="text" id="input">
        <button onclick="send()">发送</button>
    </div>
    <!-- 展示消息 -->
    <div id="show"></div>
</div>
<script src='./jquery-3.6.0.min.js'></script>
<script src='./layui/layui.js'></script>
<script>
    layui.define(function () {
        var layer = layui.layer, form = layui.form, table = layui.table;
    });
    console.log(1111)
    let wsServer = 'ws://127.0.0.1:9514';
    let websocket = new WebSocket(wsServer);
    websocket.onopen = function (res) {
        $('#welcome').text('连接成功');
    };

    websocket.onclose = function (res) {
        $('#welcome').text('连接已关闭');
    };

    websocket.onmessage = function (res) {
        console.log('message', res);
        let msg = '<div class="left">' + res.data + '</div>';
        // let msg = '<div class="right">' + res.data + '</div>';
        $('#show').append(msg);
    };

    websocket.onerror = function (res, e) {
        $('#show').append(res.data);
    };

    function send() {
        let data = $('#input').val();
        if (data) {
            websocket.send(data);
        } else {
            alert('不能发送空白消息');
        }
    }

</script>
</body>
</html>